//package com.xiaoyu.awakening.common.enterprisewx;
//
//import com.alibaba.fastjson2.JSONObject;
//import com.tencent.wework.Finance;
//import com.xiaoyu.awakening.common.enterprisewx.dto.WXMsgDetailsDto;
//import com.xiaoyu.awakening.common.enterprisewx.dto.WXMsgPullReq;
//import com.xiaoyu.awakening.common.enterprisewx.dto.WXMsgSaveFileDto;
//import lombok.extern.slf4j.Slf4j;
//import org.apache.commons.lang3.StringUtils;
//
//import javax.crypto.Cipher;
//import java.math.BigInteger;
//import java.nio.charset.StandardCharsets;
//import java.security.KeyFactory;
//import java.security.PrivateKey;
//import java.security.spec.RSAPrivateCrtKeySpec;
//import java.util.*;
//
//import sun.security.util.DerInputStream;
//import sun.security.util.DerValue;
//
///**
// * WXMsgSaveFileParse
// *
// * @author wangxiaoyu
// * @date 2024/4/25 17:08
// * @since v1.0
// */
//@Slf4j
//public abstract class WXMsgSaveFileParse {
//    public abstract WXMsgPullReq loadWXMsgPullConfig();
//
//    public abstract Integer loadWXMsgPullSeq();
//
//    public abstract boolean saveWXMsgPullSeq(Integer seq);
//
//    public void pullMsgAndParse() {
//        WXMsgPullReq wxMsgPullReqConfig = loadWXMsgPullConfig();
//        if (Objects.isNull(wxMsgPullReqConfig) || !wxMsgPullReqConfig.isEnable()) {
//            return;
//        }
//        Integer seq = loadWXMsgPullSeq();
//        WXMsgSaveFileDto wxMsgSaveFileDto = pullDataAndParse(wxMsgPullReqConfig, seq);
//        boolean successFlag = Objects.nonNull(wxMsgSaveFileDto) && Objects.nonNull(wxMsgSaveFileDto.getChatdata());
//        if (successFlag) {
//            seq = wxMsgSaveFileDto.getChatdata().get(wxMsgSaveFileDto.getChatdata().size() - 1).getSeq();
//            saveWXMsgPullSeq(seq);
//        } else {
//            log.warn("pull and parse wechat data failed or empty,seq:{}", seq);
//        }
//    }
//
//    private WXMsgSaveFileDto pullDataAndParse(WXMsgPullReq wxMsgPullReq, Integer seq) {
//        try {
//            // 初始化
//            long sdk = Finance.NewSdk();
//            long initRet;
//            initRet = Finance.Init(sdk, wxMsgPullReq.getCorPid(), wxMsgPullReq.getSecret());
//            if (initRet != 0) {
//                Finance.DestroySdk(sdk);
////                log.error("WXMsgSaveFileParse init sdk err ret:{}", initRet);
//                return null;
//            }
//            // 拉取会话存档
//            //每次使用GetChatData拉取存档前需要调用NewSlice获取一个slice，在使用完slice中数据后，还需要调用FreeSlice释放。
//            long slice = Finance.NewSlice();
//            initRet = Finance.GetChatData(sdk, seq, wxMsgPullReq.getLimit(), wxMsgPullReq.getProxy(), wxMsgPullReq.getProxyPasswd(), wxMsgPullReq.getPullTimeout(), slice);
//            if (initRet != 0) {
////                log.error("WXMsgSaveFileParse get data slice err ret:{}", initRet);
//                Finance.FreeSlice(slice);
//                return null;
//            }
//            String metadata = Finance.GetContentFromSlice(slice);
//            Finance.FreeSlice(slice);
//            if (StringUtils.isBlank(metadata)) {
//                return null;
//            }
//
//            WXMsgSaveFileDto wxMsgSaveFileDto = JSONObject.parseObject(metadata, WXMsgSaveFileDto.class);
//            if (wxMsgSaveFileDto.getErrcode() != 0) {
//                log.error("get wx msg failed");
//                return null;
//            }
//            List<WXMsgSaveFileDto.ChatData> chatDataList = wxMsgSaveFileDto.getChatdata();
//            int pullTotal = Objects.nonNull(chatDataList) ? chatDataList.size() : 0;
//            log.info("get wx msg total:{}", pullTotal);
//            if (pullTotal > 0) {
//                chatDataList.forEach(chatData -> {
//                    int dataRet;
//                    String encrypt_key = "";
//                    try {
//                        encrypt_key = rsaDecodeByPKCS1(wxMsgPullReq.getPrivateKey(), chatData.getEncrypt_random_key());
//                    } catch (Exception e) {
//                        log.error("rsaDecodeByPKCS1 error,seq:{},encrypt_random_key:{},skip--error:", chatData.getSeq(), chatData.getEncrypt_random_key(), e);
//                        return;
//                    }
//                    String encrypt_chat_msg = chatData.getEncrypt_chat_msg();
//                    //每次使用DecryptData解密会话存档前需要调用NewSlice获取一个slice，在使用完slice中数据后，还需要调用FreeSlice释放。
//                    long msg = Finance.NewSlice();
//                    dataRet = Finance.DecryptData(sdk, encrypt_key, encrypt_chat_msg, msg);
//                    if (dataRet != 0) {
//                        log.error("WXMsgSaveFileParse DecryptData slice err ret:{}", dataRet);
//                        Finance.FreeSlice(msg);
//                        return;
//                    }
//                    String parsedContent = Finance.GetContentFromSlice(msg);
//                    Finance.FreeSlice(msg);
//                    if (StringUtils.isBlank(parsedContent)) {
//                        log.warn("WXMsgSaveFileParse DecryptData empty");
//                        return;
//                    }
//                    WXMsgDetailsDto wxMsgDetailsDto = JSONObject.parseObject(parsedContent, WXMsgDetailsDto.class);
//                    chatData.setFormatDetails(wxMsgDetailsDto);
//                    log.info("WXMsgSaveFileParse DecryptData success:{}", wxMsgDetailsDto.getMsgid());
//                });
//            }
//            return wxMsgSaveFileDto;
//        } catch (Throwable e) {
//            log.error("WXMsgSaveFileParse error:", e);
//            return null;
//        }
//    }
//
//    private String rsaDecodeByPKCS1(String privateKeyStr, String rsaContent) throws Exception {
//        String privateKeyTemp = privateKeyStr.replaceAll("\\n", "")
//                .replace("-----BEGIN RSA PRIVATE KEY-----", "")
//                .replace("-----END RSA PRIVATE KEY-----", "");
//        byte[] bytes = Base64.getDecoder().decode(privateKeyTemp);
//        DerInputStream derReader = new DerInputStream(bytes);
//        DerValue[] seq = derReader.getSequence(0);
//        BigInteger modulus = seq[1].getBigInteger();
//        BigInteger publicExp = seq[2].getBigInteger();
//        BigInteger privateExp = seq[3].getBigInteger();
//        BigInteger prime1 = seq[4].getBigInteger();
//        BigInteger prime2 = seq[5].getBigInteger();
//        BigInteger exp1 = seq[6].getBigInteger();
//        BigInteger exp2 = seq[7].getBigInteger();
//        BigInteger crtCoef = seq[8].getBigInteger();
//
//        RSAPrivateCrtKeySpec keySpec = new RSAPrivateCrtKeySpec(modulus, publicExp, privateExp, prime1, prime2, exp1, exp2, crtCoef);
//        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
//        PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
//
//        byte[] decodeRsaByte = Base64.getDecoder().decode(rsaContent);
//        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
//        cipher.init(Cipher.DECRYPT_MODE, privateKey);
//        byte[] res = cipher.doFinal(decodeRsaByte);
//        return new String(res, StandardCharsets.UTF_8);
//    }
//}
